"""
此为分页器，包含两部分：
    ## framework(self) ：函数为框架设置，返回一个水平框架，用于跟其他ui搭配
    ## pageController(self,signal)：页码跳转，初始化该类时可出入需要分页的数据（np、元组形式），返回的是需要的某页的数据，之后还需要对数据输出到前端
未实现部分：
    框架与ui的搭配输出
"""
import sys

from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import *
import numpy as np
import math

from backEnd.database.DBService.adminDB import select_page, select
from foreEnd.tools import regular_restricted_input


# 改了一下继承关系，方便调用

class page(QHBoxLayout):
    control_signal = pyqtSignal(list)  # 信号
    def __init__(self, table_name, table_name_2=None):
        super(page, self).__init__()
        self.table_name = table_name
        self.table_name_2 = table_name_2
        length2 = 0
        if self.table_name_2 is not None:
            work, result = select(self.table_name_2)
            if work == 1:
                length2 = len(result)  # 数据总量
            else:
                print(result)
        work, result = select(self.table_name)
        if work == 1:
            self.length = len(result) + length2  # 数据总量
        else:
            print(result)
        self.numShow = 10  # 一次展示的信息量，可修改
        self.totalPage = math.ceil(self.length / self.numShow)  # 总页数

        self.initUI()
        regular_restricted_input(self.skipPage, "page")
        self.add_connection()

    def initUI(self):
        """
        分页器水平框架
        """
        # 界面设置
        self.homePage = QPushButton("首页")
        self.prePage = QPushButton("<上一页")
        self.curPage = QLabel("1")  # 当前页
        self.nextPage = QPushButton("下一页>")
        self.finalPage = QPushButton("尾页")
        self.total = QLabel("共" + str(self.totalPage) + "页")  # 总页数，参数可改
        skipLable_0 = QLabel("跳到")
        self.skipPage = QLineEdit()  # 文本框（跳到某页）
        skipLabel_1 = QLabel("页")
        self.confirmSkip = QPushButton("确定")
        # 连接槽
        self.homePage.clicked.connect(self.__home_page)
        self.prePage.clicked.connect(self.__pre_page)
        self.nextPage.clicked.connect(self.__next_page)
        self.finalPage.clicked.connect(self.__final_page)
        self.confirmSkip.clicked.connect(self.__confirm_skip)
        # 添加入水平布局
        self.addStretch(1)  # 间隔（弹簧）
        self.addWidget(self.homePage)
        self.addWidget(self.prePage)
        self.addWidget(self.curPage)
        self.addWidget(self.nextPage)
        self.addWidget(self.finalPage)
        self.addWidget(self.total)
        self.addWidget(skipLable_0)
        self.addWidget(self.skipPage)
        self.addWidget(skipLabel_1)
        self.addWidget(self.confirmSkip)
        self.addStretch(1)

    def add_connection(self):
        self.control_signal.connect(self.pageController)  # 信号连接槽

    # 信号发射
    def __home_page(self):
        """点击首页信号"""
        self.control_signal.emit(["home", self.curPage.text()])

    def __pre_page(self):
        """点击上一页信号"""
        self.control_signal.emit(["pre", self.curPage.text()])

    def __next_page(self):
        """点击下一页信号"""
        self.control_signal.emit(["next", self.curPage.text()])

    def __final_page(self):
        """尾页点击信号"""
        self.control_signal.emit(["final", self.curPage.text()])

    def __confirm_skip(self):
        """跳转页码确定"""
        self.control_signal.emit(["confirm", self.skipPage.text()])

    # 页码跳转，其实返回的是数据，需要对数据再输出到前端
    def pageController(self, signal):
        # 发生点击事件时，先对分页器进行更新
        self.refresh()
        if "home" == signal[0]:
            self.curPage.setText('1')  # 修改当前页

        elif "pre" == signal[0]:
            if 1 == int(signal[1]):
                QMessageBox.information(self.widget(), "提示", "已经是第一页了", QMessageBox.Yes)
                return
            self.curPage.setText(str(int(signal[1]) - 1))  # 修改当前页

        elif "next" == signal[0]:
            if self.totalPage == int(signal[1]):
                QMessageBox.information(self.widget(), "提示", "已经是最后一页了", QMessageBox.Yes)
                return
            self.curPage.setText(str(int(signal[1]) + 1))  # 修改当前页

        elif "final" == signal[0]:
            self.curPage.setText(str(self.totalPage))  # 修改当前页

        elif "confirm" == signal[0]:
            if signal[1] == '':
                QMessageBox.information(self.widget(), "提示", "请输入跳转页码", QMessageBox.Yes)
                return
            if self.totalPage < int(signal[1]) or int(signal[1]) < 0:
                QMessageBox.information(self.widget(), "提示", "跳转页码超出范围", QMessageBox.Yes)
                return
            self.curPage.setText(signal[1])

    # 当发生删除或者插入操作时，更新分页器的参数
    def refresh(self):
        length2 = 0
        if self.table_name_2 is not None:
            work, result = select(self.table_name_2)
            if work == 1:
                length2 = len(result)  # 数据总量
            else:
                print(result)
        work, result = select(self.table_name)
        if work == 1:
            self.length = len(result) + length2 # 数据总量
        else:
            print(result)

        self.totalPage = math.ceil(self.length / self.numShow)  # 总页数
        self.total.setText("共" + str(self.totalPage) + "页")

        offsetNum = (int(self.curPage.text()) - 1) * self.numShow
        work, result = select_page(self.table_name, self.numShow, offsetNum)
        if work == -1:
            self.curPage.setText(str(int(self.curPage.text()) - 1))  # 修改当前页
